#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

void pauseHourse(int hours)
{
    int i=0;
    int hoursetick=0;

    hoursetick=hours*2;
    for(i=0;i<hoursetick;i++)
    {
        sleep(15);
    }
}


void AddLog(char *buf)
{
	FILE *fp = fopen("/mnt/nandflash/checkcpu.log", "a+");
	char log[1024] = {0};
	
	if(!fp){
		return ;
	}
	
	time_t t = time(NULL);
	struct tm *lt = localtime(&t);
	
	sprintf(log, "%02d-%02d:%02d:%02d@ %s\n",lt->tm_mday, lt->tm_hour, lt->tm_min,
									lt->tm_sec, buf);
	printf("%s",log);
	fwrite(log, strlen(log), sizeof(char), fp);
	fclose(fp);
	
	return ;
	return ;
	return ;
	
}

void GetCpuPercent(char *proc)
{
	char buf[128] = {0};
	
	FILE *fp = popen("top -n 1", "r");
	if(NULL == fp){
		return ;
	}
	
	while(!feof(fp)){
		memset(buf, 0 , sizeof(buf));
		fgets(buf, sizeof(buf), fp);
		if(strstr(buf, proc)){
			AddLog(buf);
			break;
		}
	}
	pclose(fp);
}

int main()
{
   char commond1[80]="date >> /mnt/nandflash/checkcpu.log &";
   char commond[512]="top -n 1 | grep TZ_GW_lora >> /mnt/nandflash/checkcpu.log  &";
   
   while(1)
   {
    GetCpuPercent("TZ_GW_lora");
    sleep(120);
    //pauseHourse(1);
   } 

   return 0;
}